package com.sdkj.fixed.asset.assets.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.AssetInfoChangeAssetExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.AssetInfoChangeExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.out_vo.UserInfo;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author niuliwei
 * @description 实物信息变更
 * @date 2020/7/27 11:14
 */
@Service
public class AssetChangeService extends BaseService<AssetInfoChange> {

    private final static Logger log = LoggerFactory.getLogger(AssetChangeService.class);

    @Autowired
    private AssetInfoChangeMapper infoChangeMapper;
    @Autowired
    private AssetInfoChangeAsstesMapper infoChangeAsstesMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Resource
    private WarehouseMapper warehouseMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Autowired
    private AssetSupplierMapper supplierMapper;
    @Autowired
    private SetSupplierMapper setSupplierMapper;
    @Autowired
    private AssetReportMapper assetReportMapper;
    @Autowired
    private PushManagementMapper pushMapper;
    @Autowired
    private AssetReportService assetReportService;

    @Override
    public BaseMapper getMapper() {
        return infoChangeMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }

    /**
     * 实物信息变更-新增
     * @param change
     * @return
     */
    public AssetInfoChange add(AssetInfoChangeExtend change){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        if(StringUtils.isNotBlank(change.getUser())) {
            UserInfo user = assetReportMapper.selectUser(change.getUser());
            change.setUseCompany(user.getCompanyId());
            change.setUseDepartment(user.getDeptId());
        }

        change.setNumber(getNumber("QT", orgId));
        change.setDate(change.getDate());
        change.setIsDeleted(0);
        change.setCreateUser(userId);
        change.setCreateDate(TimeTool.getCurrentTimeStr());
        change.setUpdateUser(userId);
        change.setUpdateDate(TimeTool.getCurrentTimeStr());
        change.setOrgId(orgId);
        infoChangeMapper.insertSelective(change);

        historyMapper.batchInsert(change.getAssetIdList() ,change.getId(),5);

        List<String> assetCodeList = new ArrayList<>();

        for (String str : change.getAssetIdList()) {
            //查询之前资产的数据，保存在实物明细中
            AssetInfoChangeAsstes asset = new AssetInfoChangeAsstes();
            asset.setMaterialInfoChangeId(change.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());

            WarehouseResult warehouse = warehouseService.queryByAssetId(str);

            assetCodeList.add(warehouse.getAssetCode());

            asset.setAssetName(warehouse.getAssetName());
            asset.setAssetClassId(warehouse.getAssetClassId());
            asset.setStandardModel(warehouse.getStandardModel());
            asset.setSpecificationModel(warehouse.getSpecificationModel());
            asset.setUnitMeasurement(warehouse.getUnitMeasurement());
            asset.setPurchaseTime(warehouse.getPurchaseTime());
            asset.setSnNumber(warehouse.getSnNumber());
            asset.setSource(warehouse.getSource());
            asset.setHandlerUser(warehouse.getHandlerUser());
            asset.setHandlerUserId(warehouse.getHandlerUserId());
            asset.setUseCompany(warehouse.getUseCompany());
            asset.setUseDepartment(warehouse.getUseDepartment());
            asset.setStorageLocation(warehouse.getStorageLocation());
            asset.setServiceLife(warehouse.getServiceLife());
            asset.setArea(warehouse.getArea());
            asset.setRemark(warehouse.getRemark());
            asset.setPhoto(warehouse.getPhoto());
            infoChangeAsstesMapper.insertSelective(asset);

            stateLog(str, "实物信息变更", warehouse, change, userId);

            if(StringUtils.isNotBlank(change.getSupplierId())) {
                SetSupplier setSupplier = setSupplierMapper.selectByPrimaryKey(change.getSupplierId());
                AssetSupplier supplier1 = new AssetSupplier();
                supplier1.setSupplierId(change.getSupplierId());
                supplier1.setSupplierName(setSupplier.getName());

                Example example1 = new Example(AssetSupplier.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("assetId", str);

                List<AssetSupplier> count = supplierMapper.selectByExample(example1);
                if (CollectionUtil.isNotEmpty(count)) {
                    supplierMapper.updateByExampleSelective(supplier1, example1);
                } else {
                    supplier1.setAssetId(str);
                    supplierMapper.insertSelective(supplier1);
                }
            }

            //添加资产使用记录
            if(StringUtils.isNotBlank(change.getUser())) {
                String[] split = DateTools.dateToString(new Date(), "yyyy-MM-dd").split("-");
                AssetReport assetReport = new AssetReport();
                assetReport.setAssetId(str);
                assetReport.setArYear(split[0]);
                assetReport.setArMonth(split[1]);
                assetReport.setArDay(split[2]);
                assetReport.setUseType(2);
                assetReport.setUseUserId(change.getUser());
                assetReportService.insertReport(assetReport);
            }
        }

        //修改资产基本信息
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("assetId", change.getAssetIdList());
        Warehouse warehouse = new Warehouse();
        warehouse.setAssetName(change.getAssetName());
        warehouse.setAssetClassId(change.getAssetClassId());
        warehouse.setStandardModel(change.getStandardModel());
        warehouse.setSpecificationModel(change.getSpecificationModel());
        warehouse.setUnitMeasurement(change.getUnitMeasurement());
        warehouse.setPurchaseTime(change.getPurchaseTime());
        warehouse.setSnNumber(change.getSnNumber());
        warehouse.setSource(change.getSource());
        warehouse.setHandlerUser(change.getUserName());
        warehouse.setHandlerUserId(change.getUser());
        warehouse.setUseCompany(change.getUseCompany());
        warehouse.setUseDepartment(change.getUseDepartment());
        if(StringUtils.isNotBlank(change.getUser())){
            UserInfo user = assetReportMapper.selectUser(change.getUser());
            warehouse.setState("在用");
            warehouse.setUseCompany(user.getCompanyId());
            warehouse.setUseDepartment(user.getDeptId());

            String[] asia = {change.getUser()};
            String notification_title = "实物信息变更";
            String msg_title = "实物信息变更";
            String msg_content = "实物信息变更, 单据编号：" + change.getNumber();
            log.info("实物信息变更,消息推送人："+ JSONObject.toJSONString(asia));
            JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(change.getUser());
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        }
        warehouse.setStorageLocation(change.getStorageLocation());
        warehouse.setServiceLife(change.getServiceLife());
        warehouse.setArea(change.getArea());
        warehouse.setRemark(change.getRemark());
        warehouse.setPhoto(change.getPhoto());
        warehouse.setUpdateUser(userId);
        warehouse.setUpdateTime(TimeTool.getCurrentTimeStr());
        warehouseMapper.updateByExampleSelective(warehouse, example);

        return change;
    }

    /**
     * 实物信息变更-分页查询
     * @param param
     * @return
     */
    public List<AssetInfoChangeExtend> getAllPage(PageParams<SelPrams> param){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<AssetInfoChangeExtend> list = infoChangeMapper.getChange(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId, null);
        return list;
    }

    /**
     * 实物信息变更-查看详情
     * @param id
     * @return
     */
    public AssetInfoChangeExtend selById(String id){
        AssetInfoChangeExtend extend = infoChangeMapper.selById(id);
        List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),5);
        extend.setResults(results);
        return extend;
    }

    /**
     * 实物信息变更-查看详情
     * @param id
     * @return
     */
    public AssetInfoChangeExtend print(String id){
        AssetInfoChangeExtend extend = infoChangeMapper.selById(id);
        List<AssetInfoChangeAssetExtend> list = infoChangeMapper.changeBefor(id);
        extend.setInfoChangeAssetExtendList(list);
        return extend;
    }


    /**
     * 资产处理日志
     * @param assetId
     * @param modelName
     * @param warehouse
     * @param change
     */
    public void stateLog(String assetId, String modelName, WarehouseResult warehouse, AssetInfoChangeExtend change, String userId){
        String beforeSource = warehouse.getSource();
        if(StringUtils.isNotBlank(beforeSource)){
            switch (beforeSource) {
                case "1":
                    beforeSource = "购入";
                    break;
                case "2":
                    beforeSource = "自建";
                    break;
                case "3":
                    beforeSource = "租赁";
                    break;
                case "4":
                    beforeSource = "捐赠";
                    break;
                case "5":
                    beforeSource = "其他";
                    break;
                case "6":
                    beforeSource = "内部购入";
                    break;
                default:
                    beforeSource = "";
                    break;
            }
        }
        String afterSource = change.getSource();
        if(StringUtils.isNotBlank(afterSource)){
            switch (afterSource) {
                case "1":
                    afterSource = "购入";
                    break;
                case "2":
                    afterSource = "自建";
                    break;
                case "3":
                    afterSource = "租赁";
                    break;
                case "4":
                    afterSource = "捐赠";
                    break;
                case "5":
                    afterSource = "其他";
                    break;
                case "6":
                    afterSource = "内部购入";
                    break;
                default:
                    afterSource = "";
                    break;
            }
        }

        //资产处理日志记录
        LogContext log = new LogContext();
        log.setBeforeassetName(warehouse.getAssetName());
        log.setBeforeassetClassName(warehouse.getAssetClassName());
        log.setBeforestandardModel(warehouse.getStandardModel());
        log.setBeforespecificationModel(warehouse.getSpecificationModel());
        log.setBeforeunitMeasurement(warehouse.getUnitMeasurement());
        log.setBeforesnNumber(warehouse.getSnNumber());
        log.setBeforesource(beforeSource);
        log.setBeforepurchaseTime(warehouse.getPurchaseTime());
        log.setBeforeuseCompanyName(warehouse.getUseCompanyName());
        log.setBeforeuseDepartmentName(warehouse.getUseDeptName());
        log.setBeforehandlerUserName(warehouse.getHandlerUser());
        log.setBeforeserviceLife(warehouse.getServiceLife());
        log.setBeforeareaName(warehouse.getAreaName());
        log.setBeforestorageLocation(warehouse.getStorageLocation());
        log.setBeforeremark(warehouse.getRemark());
        log.setBeforephoto(warehouse.getPhoto());
        log.setAfterassetName(change.getAssetName());
        log.setAfterassetClassName(change.getClassName());
        log.setAfterstandardModel(change.getStandardModel());
        log.setAfterspecificationModel(change.getSpecificationModel());
        log.setAfterunitMeasurement(change.getUnitMeasurement());
        log.setAftersnNumber(change.getSnNumber());
        log.setAftersource(afterSource);
        log.setAfterpurchaseTime(change.getPurchaseTime());
        log.setAfteruseCompanyName(change.getUseCompanyName());
        log.setAfteruseDepartmentName(change.getUseDepartmentName());
        log.setAfterhandlerUserName(change.getUserName());
        log.setAfterserviceLife(change.getServiceLife());
        log.setAfterareaName(change.getAreaName());
        log.setAfterstorageLocation(change.getStorageLocation());
        log.setAfterremark(change.getRemark());
        log.setAfterphoto(change.getPhoto());
        String logContent = "资产【"+warehouse.getAssetName()+"】"+ modelName +"处置；" +  ChangLogUtil.simpleLogContxt(log);

        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType(modelName);
        assetLog.setHandlerId(userId);
        assetLog.setHandlerUser(change.getHandleUserName());
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(userId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }

}
